import React, { useState } from 'react';
import styles from './index.less';
import { Input, Modal, Space, Tooltip } from 'antd';
import { PageLoading, TRMessage } from '@/components';
import { DeleteOutlined, FormOutlined } from '@/utils/antdIcons';
import {
  deleteTemplateFn,
  editTemplateFn,
  saveTemplateFn,
  timeQuanTunId,
} from '../../../../services';
import { HttpCode } from '@/utils/contacts';
import { arrToObj, initTimeEnum } from '../../../Modals/helper';

const TIME_ENUM = initTimeEnum();
export const Template = ({
  loading,
  getTemplate,
  setTableData,
  templateData = {},
  setTemplateData,
  dataSource = [],
}) => {
  const [modalLoading, setModalLoading] = useState(false);

  const editData = (e, v) => {
    e.stopPropagation();
    setTemplateData({
      visible: true,
      editData: v,
      type: 0,
    });
  };

  const deleteData = (e, v) => {
    e.stopPropagation();
    Modal.confirm({
      style: { marginTop: '20%' },
      title: '确认删除' + v.templateName + '吗?',
      okText: '确认',
      cancelText: '取消',
      onOk: async () => {
        const res = await deleteTemplateFn({
          templateId: v.id,
        });
        if (res?.statusCode === HttpCode.SUCCESS) {
          getTemplate();
        } else {
          TRMessage.error(res?.message || '系统异常');
        }
      },
    });
  };

  const importTemplate = (v) => {
    Modal.confirm({
      style: { marginTop: '20%' },
      title: '确认引用' + v?.templateName + '模板?',
      okText: '确认',
      cancelText: '取消',
      onOk: async () => {
        const res = await timeQuanTunId({
          templateId: v.id,
        });
        if (res?.statusCode === HttpCode.SUCCESS) {
          const value = res?.results?.slaves || [];
          const obj = arrToObj(value);
          setTableData({
            dataSourceObj: obj,
          });
        } else {
          TRMessage.error(res?.message || '系统异常');
        }
      },
    });
  };
  const handleCancel = () => {
    setTemplateData({
      visible: false,
    });
  };

  const editTemplate = async (flag = false) => {
    const res = await editTemplateFn({
      flag,
      templateId: templateData.editData.id,
      templateName: templateData.editData.templateName,
    });
    if (res?.statusCode === HttpCode.SUCCESS) {
      handleCancel();
      getTemplate();
    } else if (res?.statusCode === '2000') {
      Modal.confirm({
        style: { marginTop: '20%' },
        title: res?.message,
        okText: '确定',
        cancelText: '取消',
        onOk: async () => {
          await editTemplate(true);
        },
      });
    } else {
      TRMessage.error(res?.message || '系统异常');
    }
  };

  const saveTemplate = async (flag = false) => {
    const periodList = dataSource?.map((i) => ({
      ...i,
      startTime: TIME_ENUM[i?.startTime],
      endTime: TIME_ENUM[i?.endTime],
    }));
    const res = await saveTemplateFn({
      flag,
      periodList,
      templateId: templateData.editData.id,
      templateName: templateData.editData.templateName,
    });
    if (res?.statusCode === HttpCode.SUCCESS) {
      handleCancel();
      getTemplate();
    } else if (res?.statusCode === '2000') {
      Modal.confirm({
        style: { marginTop: '20%' },
        title: res?.message,
        okText: '确定',
        cancelText: '取消',
        onOk: async () => {
          await saveTemplate(true);
        },
      });
    } else {
      TRMessage.error(res?.message || '系统异常');
    }
  };

  const handleOk = async () => {
    setModalLoading(true);
    if (templateData.type) {
      await saveTemplate();
    } else {
      await editTemplate();
    }
    setModalLoading(false);
  };

  const changeName = (e) => {
    const value = templateData.editData;
    value.templateName = e.target.value;
    setTemplateData({
      editData: value,
    });
  };

  const _getLine = (i) => {
    const isCustom = i?.templateType === 'custom';
    return (
      <div key={i.id} className={styles.list} onClick={() => importTemplate(i)}>
        <div className={styles.name}>
          <Tooltip
            placement={'topLeft'}
            title={<span>{i?.templateName || ''}</span>}
            destroyTooltipOnHide
          >
            {i?.templateName || ''}
          </Tooltip>
          <Space>
            {isCustom && (
              <>
                <FormOutlined className={styles.editIcon} onClick={(e) => editData(e, i)} />
                <DeleteOutlined className={styles.deleteIcon} onClick={(e) => deleteData(e, i)} />
              </>
            )}
          </Space>
        </div>
        {isCustom && <div className={styles.person}>·修改人：{i?.updateName}</div>}
      </div>
    );
  };

  if (loading) return <PageLoading />;
  return (
    <>
      <div className={styles.title}>套用模板</div>
      <div className={styles.content}>{templateData.list.map((i) => _getLine(i))}</div>
      <Modal
        title={templateData?.type ? '存为模板' : '修改名称'}
        onOk={handleOk}
        onCancel={handleCancel}
        confirmLoading={modalLoading}
        okText={'保存'}
        className={styles.editModal}
        style={{ top: '40%' }}
        cancelText={'取消'}
        visible={templateData.visible}
      >
        <Input
          value={templateData?.editData?.templateName || ''}
          onChange={changeName}
          placeholder={'自定义名称'}
        />
      </Modal>
    </>
  );
};
